<?php

namespace app\modules\Member\controllers;

use Yii;
use app\modules\Member\models\Member;
use app\modules\Member\models\MemberSearch;
use app\modules\Order\models\Order;
use app\modules\Order\models\OrderRoom;
use app\modules\Product\models\Product;
use dektrium\user\models\LoginForm;
use dektrium\user\models\User;
use app\modules\Order\models\OrderCustomer;
use app\modules\Order\models\OrderRoomCustomer;
use dektrium\user\models\Profile;
use yii\web\Controller;
use yii\web\Session;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\Pagination;
use yii\data\ArrayDataProvider;

/**
 * MemberController implements the CRUD actions for Member model.
 */
class MemberController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
		return [
			'verbs' => [
				'class' => VerbFilter::className(),
				'actions' => [
					'delete' => ['post'],
				],
			],
			'access' => [
				'class' => AccessControl::className(),
                'only' => ['index','create','view','update','delete','others'],
				'rules' => [
					[
						'allow' => true, 
						'actions' => ['index','create','view','update','delete','others'], 
						'roles' => ['@'],
						'matchCallback' => function ($rule, $action) {
							return  (Yii::$app->user->identity->username == 'admin') ? true : false;
						}
					],
				],
			],
		];
    }

    //个人中心
    public function actionMember()
    {
        $this->layout = "//mui";
        return  $this->render('member');
    }

     // 退出
    public function actionLogout(){
      
        \Yii::$app->getUser()->logout();

        echo "<script>
                localStorage.clear();
                window.location.href='/member/member/login'; 
              </script>";   
    }

 

    // 修改密码 
    public function actionPassword(){

        $this->layout = "//mui";
        $data = Yii::$app->request->get();

        if(!isset($data['id']) && empty($data['id'])){
        	return $this->redirect(['edit-password']);
        }

        $model = $this->findModel($data['id']);

        $model->scenario = 'password';

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
           
           $model->confirmPassword = $model->password = Yii::$app->getSecurity()->generatePasswordHash($model->password);

            if($model->save()){
                return $this->redirect(['member']);
            }
        }
        $model->password = "";
        $model->confirmPassword = "";

        return $this->render('password', [
            'model' => $model,
        ]);
    }

    //中转跳转
    public function actionEditPassword(){
      	$this->layout = "//mui";
      	return  $this->render('edit-password');
    }

    //订单列表
    public function actionOrder($product_id = 0)
    {   
        $this->layout = "//mui";
        $post = yii::$app->request->get();
        $product_id = 0;

        $msg = "暂无订单";

        if(\Yii::$app->user->isGuest){
            return $this->redirect("/member/member/login-url"); 
        }
    
        $query = Order::find();
        $query->joinwith('product');
        if(\Yii::$app->user->identity->username !== 'admin'){
           $query->andWhere(['order.member_id'=>\Yii::$app->user->identity->id]);
        }
        if(!empty($post['product_id'])){
            $query->andWhere(['product_id'=>$post['product_id']]);
            $product_id = $post['product_id'];
        }
       
        $query = $query->orderBy(['order.relation'=>SORT_DESC, 'order.status'=> SORT_ASC]);

        $pages = new Pagination(['totalCount' =>$query->count(), 'pageSize' => '20']);

        $order = $query->offset($pages->offset)->limit($pages->limit)->all();



        $query2 = Order::find()->joinwith('product');
        if(\Yii::$app->user->identity->username !== 'admin'){
           $query2->andWhere(['order.member_id'=>\Yii::$app->user->identity->id]);
        }
        $all_num = $query2->count();

        $query3 = (new \yii\db\Query())
              ->select("order.id,count(order.product_id) as num,order.product_id,order.member_id,product.name,product.go_time")
              ->from('order')
              ->leftJoin('product','product.id = order.product_id');

        if(\Yii::$app->user->identity->username !== 'admin'){
           $query3->andWhere(['order.member_id'=>\Yii::$app->user->identity->id]);
        }
        
        $lines = $query3->groupBy('order.product_id')->all();

        $sellOrder = $overOrder = [];

        if(!empty($lines)){
             foreach($lines as $val){
                  if(strtotime($val['go_time']) > time()){
                      $sellOrder[] = $val; //在售船期 
                  }else{
                      $overOrder[] = $val; //过期船期 
                  }
             }
         } 

         $provider = new ArrayDataProvider([
              'allModels' => $overOrder,
              'sort' => [ 
                  'attributes' => ['go_time'],
              ],
              'pagination' => [
                  'pageSize' => 6,
                  'defaultPageSize'=>6,
                  'pageParam' => 'over-p',
              ],
        ]);
        $overOrder = $provider->getModels();

        $provider2 = new ArrayDataProvider([
              'allModels' => $sellOrder,
              'sort' => [ 
                  'attributes' => ['go_time'],
              ],
              'pagination' => [
                  'pageSize' => 6,
                  'defaultPageSize'=>6,
                  'pageParam' => 'sea-p',
              ],
        ]);
        $sellOrder = $provider2->getModels();
             
        $profile =  Profile::find()->where(['user_id'=>\yii::$app->user->id])->one();   

        return $this->render('order',['order'=>$order,'pages'=>$pages,'msg'=>$msg,'all_num'=>$all_num,'product_id'=>$product_id,'sellOrder'=>$sellOrder,'provider'=>$provider,'provider2'=>$provider2,'overOrder'=>$overOrder,'profile'=>$profile]);

    }

    //订单详情
    public function actionOrderInfo($id){

        $this->layout = "//mui";
        if(\Yii::$app->user->isGuest){
            return $this->redirect("/member/member/login-url"); 
        }
        $model = Order::findOne($id);
        return $this->render("order-info",['model'=>$model]);
    }

    //上传资料
    public function actionOrderDetail($id)
    {
        $this->layout = "//mui";
        if(\Yii::$app->user->isGuest){
            return $this->redirect("/member/member/login-url"); 
        }
        $model = Order::findOne($id);
        return $this->render("order-detail",['model'=>$model]);
    }

    //添加客户信息
    public function actionCreateCustomer()
    {
        $model = new OrderCustomer();
        $rc = new OrderRoomCustomer();
        $data = yii::$app->request->get();
        if(!empty($data)){
            $order = Order::findOne($data['order_id']);
            $model->order_id = $data['order_id'];
            $model->first_name = $data['first_name'];
            $model->last_name = $data['last_name'];
            $model->gender = 1;
            $model->passport_type = 1;
            if($model->save()){
                 $customer_id = $model->id;
                 $rc->order_id = $data['order_id'];
                 $rc->order_room_id = $data['order_room_id'];
                 $rc->customer_id = $customer_id;
                 $rc->status = 1;
                 $rc->price = $order->price;
                 if($rc->save()){
                    $res = ['code'=>1,'data'=>'','msg'=>'添加成功'];
                    print_r(json_encode($res));exit();
                 }
            }  
        }else{
            $res = ['code'=>0,'data'=>'','msg'=>'添加成功'];
            print_r(json_encode($res));exit();
        } 

    }

    //会员登录ajax
    public function actionLoginJson()
    {

        $data = Yii::$app->request->post();
        $user = User::find()->where(['username'=>$data['User']['username']])->one();
      
        if($user){

          if(Yii::$app->getSecurity()->validatePassword($data['User']['password'], $user->password_hash)){ 
                if(empty($user->profile->openId)){
                   $profile = Profile::find()->where(['user_id'=>$user->id])->one();
                   if(empty($profile)){
                      $profile = new Profile();
                      $profile->user_id = $user->id;
                   } 
                   $profile->openId = $data['User']['openId'];
                   $profile->save();
                }
                $data = ['user_id'=>$user->id,'username'=>$user->username,'email'=>$user->email];
                $res = ['code'=>1,'data'=>$data,'msg'=>'登录成功'];
                print_r(json_encode($res));
                exit();
          } 

        }

        $res = ['code'=>0,'data'=>'','msg'=>'登录失败,账号或密码错误'];
        print_r(json_encode($res));
    }

    //会员登录跳转获取openId
    public function actionLoginUrl()
    { 
      //snsapi_userinfo snsapi_base
      //$url = sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=123456#wechat_redirect", Yii::$app->params['appId'], Yii::$app->request->hostInfo.'/member/member/login', 'snsapi_userinfo');
      $url = Yii::$app->request->hostInfo.'/member/member/login';
      return $this->redirect($url);
    }

  
    //新会员登录
    public  function actionLogin()
    {

      $this->layout = "//mui";
      if (!\Yii::$app->user->isGuest) {
          return $this->redirect("/member/member/order"); 
      }

      $ret = Yii::$app->request->get();
      $openId = ['openid'=>''];

      if(isset($ret['code'])){
            $code = $ret['code']; 
            $openId = Yii::$app->weixin->getOpenId($code); 
      }

      $model = \Yii::createObject(LoginForm::className());

      $data =  \Yii::$app->getRequest()->post();

      if($model->load(\Yii::$app->getRequest()->post()) && $model->login()) {
          
          $user = User::findOne(\Yii::$app->user->id);
          if(empty($user->profile->openId)){
               $profile = Profile::find()->where(['user_id'=>$user->id])->one();
               if(empty($profile)){
                  $profile = new Profile();
                  $profile->user_id = $user->id;
               } 
               $profile->openId = $data['User']['openId'];
               $profile->save();
          }

          echo "<script>
                  localStorage.setItem('login'," . "'" . $model->login . "'" . ");
                  localStorage.setItem('passwd'," . "'" . yii::$app->authcode->authcode($model->password,'ENCODE','',0) . "'" . ");
                </script>"; 

          echo "<script> 
                 window.location.href='/member/member/order'; 
              </script>"; 
                     
      }
     
      return $this->render('login',['openId'=>$openId]);

    }

    //订单变为已付款
    public function actionCheckStatus($id)
    { 
       $model = Order::findOne($id);

       $model->status = 3;

       if($model->save()){
           return $this->redirect(Yii::$app->request->getReferrer());
       }

    }

    // 取消订单
    public function actionUnrecovery($id){//{{{

        $model = Order::findOne($id);
        // 判断是否已被分团占用
        if(!empty($model->assign_id)){
          echo "<script>
              alert('订单已分团， 不能取消, 请先在团队中移除该订单');
              window.history.back();
              </script>";      
          return false;
        }
        // 判断是否是关联订单
        if($model->isRelation > 1){
          echo "<script>
              alert('关联订单, 请先取消关联后操作');
              window.history.back();
              </script>";      
          return false;
        }
        // 判断是否拼房
        if($model->merge_id){
          echo "<script>
              alert('该订单已拼房, 请先取消拼住的舱房');
              window.history.back();
              </script>";      
          return false;
        }

        // 更改订单状态 
          /*
              1 => '占位',
              3 => '已付款',
              4 => '确认提交',
              10 => '占位-取消',
              11 => '付款-取消',
              12 => '提交-取消',   
          */
        if($model->status == 1){  // 占位取消
          
          $model->status = 10;
        }elseif($model->status == 2){	// 定金取消

			$model->status = 13;
		}elseif($model->status == 3){ // 付款取消

          $model->status = 11;
        }elseif($model->status == 4){ // 提交取消
        
          $model->status = 12;
        }

        $model->save();

        // 更改订单所属舱房的状态
        OrderRoom::updateAll(['status'=>2], sprintf('order_id = %d', $id) );

        return $this->redirect(Yii::$app->request->getReferrer());
    }//}}}

    /** 添加舱房 ***/
    public function actionEditRoom($id){//{{{
        if(empty($id)){
           return false;
        }
    
        $model = Order::findOne($id);
        $product = Product::findOne($model->product_id);
            
        $params = Yii::$app->request->post();
  
        if(isset($params['room']) ) {

            // 保存完成 设置船舱
            if($product->stock == 1){ // 国内航线 标准库存格式
              
              Yii::$app->orderblock->create($params, $model, 2);
            }elseif($product->stock == 2){ // 海外航线  自定义库存格式
              
              Yii::$app->orderblock->create2($params, $model, 2);
            }
            
            // 记录日志
            return $this->redirect(['order-info', 'id' => $model->id]);
        }
    }//}}}

    // 获取订单其它待合房订单
    public function actionMergeList($id, $room_id){//{{{
  
      $this->layout = "//mui";    
      $model = Order::findOne($id);

      if($model->merge_id){ // 已拼房
        $data = Order::find()->where(['id'=>$model->merge_id])->andWhere(['is_merge'=>2])->all();
      }else{
        $data = Order::find()->andWhere(['product_id'=>$model->product_id])->andWhere(['is_merge'=>2])->andWhere(['status'=>[1,3,4]])->andWhere(['merge_id'=>NULL])->andWhere(['!=', 'id', $model->id])->all();
      }

      return $this->render('merge-list', ['data' => $data , 'model'=>$model, 'room_id'=>$room_id]);
    }//}}}

    //添加舱房
    public function actionOrderRoom($id)
    {
      $this->layout = "//mui";
      if(!is_numeric($id)){
        return false;
      }
      $model = Order::findOne($id);
      if(empty($model)){
        return false;
      }

      return $this->render('order-room',['model'=>$model]);

    }


    //绑定微信号
    public function actionWeixin()
    {
      if(\Yii::$app->user->isGuest) {
          return  $this->redirect("/member/member/login"); 
      }
      $url = sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=123456#wechat_redirect", Yii::$app->params['appId'], Yii::$app->request->hostInfo.'/member/member/bwei', 'snsapi_base');
      //$url = Yii::$app->request->hostInfo.'/member/member/login';
      return $this->redirect($url);         
    }

    //绑定
    public function actionBwei()
    { 
      if(\Yii::$app->user->isGuest) {
            return  $this->redirect("/member/member/login"); 
      }
      $ret = Yii::$app->request->get();
      if(isset($ret['code'])){
          $code = $ret['code']; 
          $openId = Yii::$app->weixin->getOpenId($code); 
      }
      $user = User::findOne(\Yii::$app->user->id);
      if(empty($user->profile->openId)){
           $profile = Profile::find()->where(['user_id'=>$user->id])->one();
           if(empty($profile)){
              $profile = new Profile();
              $profile->user_id = $user->id;
           } 
           $profile->openId = $openId['openid'];
           $profile->save();
      }

      return $this->redirect("/member/member/order");



    }

    //ajax自动登录
    public function actionAutoLogin()
    {
        $data = yii::$app->request->post();
        $res = ['code'=>0,'data'=>'','msg'=>'添加成功'];
        if(empty($data)){
            print_r(json_encode($res));exit();
        }
        //判断是否已经登录了
        if(!yii::$app->user->isGuest){
            print_r(json_encode($res));exit();
        }else{ //未登录
            $data['login-form']['password'] = yii::$app->authcode->authcode($data['login-form']['password'],'DECODE','',0); 
            $model = \Yii::createObject(LoginForm::className());

            if($model->load($data) && $model->login()) {
                 $res = ['code'=>1,'data'=>'','msg'=>'登录成功']; 
                 print_r(json_encode($res));exit();
            }else{
                print_r(json_encode($res));exit();
            }  

        }

    }

    //上传文件
    public function actionUpload()
    {
      
      header('Content-type:text/html;charset=utf-8');
      $base64_image_content = $_POST['base64_string'];
      $customer_id = $_POST['id'];
      if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
          $type = $result[2];
          $new_file = "uploads/passport/".date('Ym')."/";

          if(!file_exists($new_file)){
              mkdir($new_file, 0755);
          }

          $new_file = $new_file.time().".{$type}";

          if(file_put_contents($new_file, base64_decode(str_replace($result[1],'',$base64_image_content)))){
               $model = OrderCustomer::find()->where(['id'=>$customer_id])->one();
               $model->passport_img = $new_file;
               if($model->save()){
                  $res = ["status"=>1,"content"=>"上传成功","url"=>$new_file];
                  print_r(json_encode($res));
               } 
            }else{
              $res = ["status"=>0,"content"=>"上传失败","url"=>""];
              print_r(json_encode($res));
            }
      }
  

    }

    
    //同业客户注册
    public function actionRegister()
    {
        $this->layout = "//mui";

        $model = new Member();

        $model->scenario = 'register';

        if ($model->load(Yii::$app->request->post()) && $model->validate()){
           
            // 密码加密
            $model->confirmPassword = $model->password = Yii::$app->getSecurity()->generatePasswordHash($model->password);
            $model->type = 2;
            $model->status = 3;

            if($model->save()){
               return $this->redirect(['success']);
            }
        }

        return  $this->render('register',['model'=>$model]);
    }

    //注册成功
    public function actionSuccess()
    {
       $this->layout = "//mui";

       return  $this->render('success');
    }

    //同业客户审核 发送邮件
    public function actionCheck($id)
    {
       $model = Member::findOne($id);
       $model->scenario = 'update';
       $model->status = 1;
       if($model->save()){
            $mail= Yii::$app->mailer->compose();
            $mail->setTo($model->mail); 
            $mail->setSubject("账号审核通知");
            $mail->setHtmlBody(sprintf("<div><p>尊敬的%s：您好！</p>
                              <p style='text-indent: 2em;'>您的账号已通过审核。</p></div>
                               <p style='font-weight: bold;float:right;margin-right:100px'>邮轮联盟</p></div>
                              ",$model->name));
            $mail->send();
       }
       return $this->redirect(['others']);
    }

    //同业客户管理
    public function actionOthers()
    {
        $searchModel = new MemberSearch();
        $dataProvider = $searchModel->o_search(Yii::$app->request->queryParams);

        return $this->render('others', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    //同业客户更新
    public  function actionMemUpdate($id)
    {
        $model = $this->findModel($id);
        $model->scenario = 'update';
       
        if ($model->load(Yii::$app->request->post())) {
            
            if($model->save()){
                return $this->redirect(['mem-view', 'id' => $model->id]);
            }
        } else {
            return $this->render('mem-update', [
                'model' => $model,
            ]);
        }  
    }

    public function actionMemView($id)
    {
        return $this->render('mem-view', [
            'model' => $this->findModel($id),
        ]);
    }


    /**
     * Lists all Member models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new MemberSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Member model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Member model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Member();

        $model->scenario = 'create';

        if ($model->load(Yii::$app->request->post()) ) {
            //$model->password = Yii::$app->getSecurity()->generatePasswordHash($model->password);
            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
				print_r($model->getErrors());
			}
        } else {
            $model->status = 1;
            $model->gender = 1;
            $model->type =1;
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Member model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        $model->scenario = 'update';

        if ($model->load(Yii::$app->request->post())) {
            // $model->password = Yii::$app->getSecurity()->generatePasswordHash($model->password);
            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Member model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Member model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Member the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Member::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
